package com.yz.crm.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.yz.crm.web.anno.JsonViewSupport;

/**
 * Created by SaintRen on 2016/8/19.
 */
public class JsonViewInterceptor extends HandlerInterceptorAdapter {
	private static final Log log = LogFactory.getLog(JsonViewInterceptor.class);


	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		HandlerMethod method = (HandlerMethod) handler;
        JsonViewSupport jvs = method.getMethodAnnotation(JsonViewSupport.class);
        if (jvs == null) {
            return;
        }
        
        try{
        	boolean enable = (boolean)modelAndView.getModel().get(jvs.enableName());
        	if (!enable){
        		return;
        	}
        }catch(NullPointerException e){
        	return ;
        }
        
        //Object model = modelAndView.getModelMap().get(jvs.modelName());
        
        //JsonViewConverter.createJson(model, response);
        
        //创建JSON视图
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setExtractValueFromSingleKeyModel(true);//不知道为何，反正加上这个就好了
        view.setModelKey(jvs.modelName());
        modelAndView.setView(view);
	}

}
